package com.example.PDFdemo.crossseal;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PDFUtil {
    private static final String TEMP_DIR = "/app" + File.separator + "temp" + File.separator;

    public void crossSealV2(String oldFilePath, String newFilePath, String src) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(oldFilePath);
        FileOutputStream outputStream = new FileOutputStream(newFilePath);
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        int n = reader.getNumberOfPages();
        Rectangle rectangle;
        PdfContentByte over;
        final List<String> splitImageList = splitImage(src, 1, n);
        float radius = this.getRadius(reader);
        float maxH = this.getMaxH(reader, radius);
        for (int i = 1; i <= n; i++) {

            //求加权后的w、h
            /*
            加权算法：
            1.获取每一页的页面大小，并且向上取整
            2.取整后的宽、高 * （72/25.4）
            3.在乘以radius
            * */
            float width = (float) Math.ceil(reader.getPageSizeWithRotation(i).getRight());
            float height = (float) Math.ceil(reader.getPageSizeWithRotation(i).getHeight());
            width = (float) (width * (72 / 25.4));
            height = (float)(height * (72 / 25.4));
            width = width * radius;
            height = height * radius;

            rectangle = reader.getPageSizeWithRotation(i);
            float x = rectangle.getRight();
            float y = rectangle.getTop();
            over = stamper.getOverContent(i);
            over.saveState();
            PdfGState state = new PdfGState();
            state.setFillOpacity(1.0f);
            over.setGState(state);

            //求s、h、y的百分比
            float Sw = (float) (113.11650176744534 / width);   //Sw = w（前端传值） / width（加权后的宽）
            float Sh = (float) (113.11650176744534 / height);  //Sh = h（前端传值）/  height（加权后的高）
            float Sy = (float) ((maxH - 169.44174911627732 - 113.11650176744534) / height);   //Sy = （ maxH - y（前端传值） - h（前端传值）） / height（加权后的高）

            Image img = Image.getInstance(splitImageList.get(i - 1));
            over.addImage(img, x * Sw / n, 0, 0, y * Sh,
                    x - x * Sw / n, y * Sy);
            over.restoreState();
        }
        stamper.close();
        outputStream.close();
        reader.close();
    }

    public void crossSeal(String oldFilePath, String newFilePath, String src) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(oldFilePath);
        FileOutputStream outputStream = new FileOutputStream(newFilePath);
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        int n = reader.getNumberOfPages();
        Rectangle rectangle;
        rectangle = reader.getPageSizeWithRotation(1);
        PdfContentByte over;
        pdfAddCommonSeal(rectangle, stamper);
//        final List<String> splitImageList = splitImage(src, 1, n);
//        float radius = this.getRadius(reader);
//        float maxH = this.getMaxH(reader, radius);
//        for (int i = 1; i <= n; i++) {
//
//            //求加权后的w、h
//            /*
//            加权算法：
//            1.获取每一页的页面大小，并且向上取整
//            2.取整后的宽、高 * （72/25.4）
//            3.在乘以radius
//            * */
//            float width = (float) Math.ceil(reader.getPageSizeWithRotation(i).getRight());
//            float height = (float) Math.ceil(reader.getPageSizeWithRotation(i).getHeight());
//            width = (float) (width * (72 / 25.4));
//            height = (float)(height * (72 / 25.4));
//            width = width * radius;
//            height = height * radius;
//
//            rectangle = reader.getPageSizeWithRotation(i);
//            float x = rectangle.getRight();
//            float y = rectangle.getTop();
//            over = stamper.getOverContent(i);
//            over.saveState();
//            PdfGState state = new PdfGState();
//            state.setFillOpacity(1.0f);
//            over.setGState(state);
//
//            //求s、h、y的百分比
//            float Sw = (float) (113.11650176744534 / width);   //Sw = w（前端传值） / width（加权后的宽）
//            float Sh = (float) (113.11650176744534 / height);  //Sh = h（前端传值）/  height（加权后的高）
//            float Sy = (float) ((maxH - 169.44174911627732 - 113.11650176744534) / height);   //Sy = （ maxH - y（前端传值） - h（前端传值）） / height（加权后的高）
//
//            Image img = Image.getInstance(splitImageList.get(i - 1));
//            over.addImage(img, x * Sw / n, 0, 0, y * Sh,
//                    x - x * Sw / n, y * Sy);
//            over.restoreState();
//        }
        stamper.close();
        outputStream.close();
        reader.close();
    }

    private List<String> splitImage(String originalImg, int rows, int cols) throws IOException {
        final long s = System.currentTimeMillis();
        // 读入大图
        File file = new File(TEMP_DIR + File.separator + originalImg.substring(originalImg.lastIndexOf("/")));
        FileUtils.copyURLToFile(new URL(originalImg), file);
        FileInputStream fis = new FileInputStream(file);
        BufferedImage image = ImageIO.read(fis);
        // 分割成 rows * cols 个小图
        int chunks = rows * cols;
        // 计算每个小图的宽度和高度
        int chunkWidth = image.getWidth() / cols;
        int chunkHeight = image.getHeight() / rows;
        int count = 0;
        BufferedImage[] images = new BufferedImage[chunks];
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                //设置小图的大小和类型
                images[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());
                //写入图像内容
                Graphics2D gr = images[count++].createGraphics();
                gr.drawImage(image, 0, 0,
                        chunkWidth, chunkHeight,
                        chunkWidth * y, chunkHeight * x,
                        chunkWidth * y + chunkWidth,
                        chunkHeight * x + chunkHeight, null);
                gr.dispose();
            }
        }
        // 输出小图
        List<String> ans = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            final String pathname = TEMP_DIR + file.getName() + "-" + i + ".png";
            ImageIO.write(images[i], "png", new File(pathname));
            ans.add(pathname);
        }
        return ans;
    }

    public float getRadius(PdfReader reader) {
        List<Float> weights = new ArrayList<>();
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            float width = (float) Math.ceil(reader.getPageSizeWithRotation(i).getRight());
            width = (float) (width * (72 / 25.4));
            weights.add(width);
        }
        float maxW = Collections.max(weights);
        float pageMaxWidth;
        if (maxW > 800) {
            pageMaxWidth = 800;
        } else {
            pageMaxWidth = maxW;
        }
        return pageMaxWidth / maxW;
    }

    public float getMaxH(PdfReader reader, float radius) {
        List<Float> heights = new ArrayList<>();
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            float height = (float) Math.ceil(reader.getPageSizeWithRotation(i).getHeight());
            height = (float) (height * (72 / 25.4)) * radius;
            heights.add(height);
        }
        return Collections.max(heights);
    }

    private static void pdfAddCommonSeal(Rectangle rectangle, PdfStamper stamper) throws DocumentException, IOException {
        // 获取 pdf 页面的宽高
        float x = rectangle.getRight();
        float y = rectangle.getTop();
        System.out.println("x：" + x);
        System.out.println("y：" + y);
        // 获取要写入原始文档页面的 PdfContentByte
        PdfContentByte over = stamper.getOverContent(1);
        over.saveState();
        PdfGState state = new PdfGState();
        // 设置填充透明度
        state.setFillOpacity(1.0f);
        over.setGState(state);
        // 获取 印章图片
        Image img = Image.getInstance("https://testyinji.gaoshan.co/oss/gs2021/20220303/a3dd0c6e00848e7a748bdc83b82528cb1ea6ba54e4e662a6c3022e7caefa68f2.png");
        // pdf 图层图片渲染
        over.addImage(img, x * 0.19975690958093328, 0, 0, y * 0.14139562720930668, 0.13012154520953337 * x, 0.7923243805758692 * y);
        over.restoreState();
    }

}
